package priv.pfz.raft.verify;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import priv.pfz.raft.verify.cmd.*;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author pengfangzhou
 * @date 2022/2/4 21:29
 */
@Slf4j
public class CommandManager {

    private static final Map<String, CmdExecutor> cmdMap = Maps.newHashMap();

    static {
        cmdMap.put("pause", new PauseCmd());
        cmdMap.put("resume", new ResumeCmd());
        cmdMap.put("status", new StatusCmd());
        cmdMap.put("stopPeer", new StopPeerCmd());
        cmdMap.put("startPeer", new StartPeerCmd());
        cmdMap.put("write", new WriteCmd());
        cmdMap.put("localRead", new LocalReadCmd());
        cmdMap.put("replicaRead", new ReplicaReadCmd());
    }

    public static boolean executeCmd(String line) {
        if (StringUtils.isBlank(line)) {
            return false;
        }

        List<String> splits = Splitter.on(Pattern.compile("\\s+")).trimResults().omitEmptyStrings().splitToList(line);
        String cmd = splits.get(0);

        //退出程序
        if ("exit".equals(cmd)) {
            return true;
        }

        List<String> params = splits.size() > 1 ? splits.subList(1, splits.size()) : Lists.newArrayList();
        CmdExecutor cmdExecutor = cmdMap.get(cmd);
        if (cmdExecutor == null) {
            log.info("no such cmd");
        } else {
            try {
                cmdExecutor.execute(params);
            } catch (Exception e) {
                log.error("execute cmd [{}] error", cmd, e);
            }
        }
        return false;
    }
}
